package net.adetech.dc.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;



import net.adetech.dc.activity.MainActivity;
import net.adetech.dc.feature.DDPushJsFeature;
import net.adetech.dc.receiver.NotificationClickReceiver;

import org.ddpush.im.util.StringUtil;
import org.ddpush.im.v1.client.appuser.Message;
import org.ddpush.im.v1.client.appuser.UDPClientBase;
import org.json.JSONObject;


import java.io.UnsupportedEncodingException;

import io.dcloud.HBuilder.Hello.R;
import io.dcloud.common.util.JSUtil;


/**
 * Created by zhangsong on 2017/9/28.
 */

public class DDPushUDPService extends Service {
    private Context mContext = this;
    private NotificationManager mNManager;
    private Notification notify;
    private UDPClient udpClient;


    public static final int ACTION_START = 1;
    public static final int ACTION_STOP = 2;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        int action = intent.getIntExtra("action",ACTION_START);
        switch (action)
        {
            case ACTION_START:
                try {
                    String userId = intent.getStringExtra("userId");
                    String ip = intent.getStringExtra("ip");
                    int port = intent.getIntExtra("port",9966);
                    Log.i("sysout", "ip:" + ip+",port:"+port+",userId:"+userId);

                    byte[] uuid = StringUtil.md5Byte(userId);

                    if (this.udpClient!=null)
                    {
                        udpClient.stop();
                    }

                    udpClient = new UDPClient(uuid, 1, ip, port);
                    udpClient.setHeartbeatInterval(50);
                    udpClient.start();
                    Log.i("sysout", "ddpush start");


                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case ACTION_STOP:
                if (udpClient!=null)
                {
                    try {
                        udpClient.stop();
                        Log.i("sysout", "ddpush stop");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }




        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Log.i("sysout", "service create");
    }


    public void notifyUser(int id,String title, String content, JSONObject pushInfo) {

        Intent clickIntent = new Intent(mContext, NotificationClickReceiver.class);
        clickIntent.putExtra("info",pushInfo.toString());
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(this, id, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder mBuilder = new Notification.Builder(this);
        mBuilder.setContentTitle(title)
                .setContentText(content)
                .setTicker(content)
                .setWhen(System.currentTimeMillis())
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.icon)
                .setContentIntent(pendingIntentClick);



        notify = mBuilder.build();


        mNManager.notify(id,notify);

    }


    public class UDPClient extends UDPClientBase {

        public UDPClient(byte[] uuid, int appid, String ip, int port) throws Exception {
            super(uuid, appid, ip, port);
        }

        @Override
        public boolean hasNetworkConnection() {
            return true;
        }

        @Override
        public void trySystemSleep() {

        }

        @Override
        public void onPushMessage(Message message) {

            try {
                String jsonString = new String(message.getData(), 5, message.getContentLength(), "UTF-8");

                try {
                    JSONObject jsonObject =  new JSONObject(jsonString);
                    String title = jsonObject.getString("title");
                    String content = jsonObject.getString("content");
                    int notifyId = jsonObject.getInt("notifyId");
                    notifyUser(notifyId,title,content,jsonObject);
                    jsonObject.put("op","1");
                    JSUtil.execCallback(DDPushJsFeature.WEBVIEW,DDPushJsFeature.CALLBACK_ID,jsonObject,JSUtil.OK,false);
                    Log.i("sysout", jsonString);
                } catch (Exception e) {
                    e.printStackTrace();
                }




            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }


    }
}
